package wh.bos.web.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import wh.bos.domain.take_delivery.Promotion;
import wh.bos.service.take_delivery.PromotionService;
import wh.bos.web.action.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion>{
	//注入promotionService
	@Autowired
	private PromotionService promotionService;
	
	private File titleImgFile;
	private String titleImgFileFileName;
	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}
	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}


	@Action(value="promotion_save",results={@Result(name="success",type="redirect"
			,location="./pages/take_delivery/promotion.html")})
	public String save() throws IOException{
		//绝对路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
		//相对路径
		String saveUrl = ServletActionContext.getRequest().getContextPath()+"/upload/";
		//设置一个随机图片名
		UUID uuid = UUID.randomUUID();
		String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		String randomFileName = uuid+ext;
		//保存图片
		FileUtils.copyFile(titleImgFile, new File(savePath+"/"+randomFileName));
		
		//将相对路径存到model中
		model.setTitleImg(saveUrl+randomFileName);
		//调用业务层
		promotionService.save(model);
		return SUCCESS;
	} 
	
	private Integer rows;
	private Integer page;
	
	public void setRows(Integer rows) {
		this.rows = rows;
	}
	public void setPage(Integer page) {
		this.page = page;
	}
	//无条件分页
	@Action(value="promotion_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable = new PageRequest(page-1, rows);
		Page<Promotion> pageDate = promotionService.findPageDate(pageable);
		//压入值栈,返回到客户端
		pushPageDateToValueStack(pageDate);
		return SUCCESS;
	}
	
}
